<!--
 * @Description: 滞留预警规则
-->
<template>
  <a-drawer title="新增滞留预警" :open="visible" @close="onClose">
    <template #closeIcon>
      <close @on-close="onClose" />
    </template>
    <a-card class="smart-margin-bottom10">
      <template #title>
        <span class="title">选择商品</span>
        <a-tooltip>
          <QuestionCircleOutlined />
          <template #title>
            <ul>
              <li>1. 勾选列表中的商品，可选择多个。</li>
              <li>2. 设置滞留预警天数，点击提交按钮即可。</li>
            </ul>
          </template>
        </a-tooltip>
      </template>
      <!---------- 查询表单form begin ----------->
      <a-form class="smart-query-form" :model="queryForm">
        <a-form-item label="商品名称" class="smart-margin-bottom0">
          <a-input v-model:value.trim="queryForm.keyword" placeholder="商品名称" autofocus allow-clear />
        </a-form-item>
        <a-form-item label="商品编码" class="smart-margin-bottom0">
          <a-input v-model:value.trim="queryForm.goods_no" placeholder="商品编码" allow-clear />
        </a-form-item>
        <a-button-group>
          <a-button type="primary" @click="onSearch">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>
          <a-button @click="resetQuery">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
        </a-button-group>
      </a-form>

      <!---------- 查询表单form end ----------->
      <a-table
        size="small"
        :dataSource="tableData"
        :columns="columns"
        :loading="tableLoading"
        rowKey="id"
        bordered
        :scroll="{ x: 'max-content', y: 360 }"
        :pagination="false"
        :showSorterTooltip="false"
        :row-selection="{
          selectedRowKeys: selectedRowKeyList,
          onChange: onSelectChange,
          preserveSelectedRowKeys: true
        }"
      >
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'img'">
            <a-image :width="text ? 30 : 50" :src="text || failImg" />
          </template>
          <template v-if="column.dataIndex === 'total_quantity'"> {{ text ?? 0 }}{{ record.unit_name }} </template>
        </template>
      </a-table>
      <div class="smart-query-table-page">
        <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
      </div>
    </a-card>
    <a-card>
      <a-space>
        <span>预警天数:</span>
        <a-input-number v-model:value="dateTime" :min="1" placeholder="请输入滞留预警天数" />
      </a-space>
    </a-card>
    <template #footer>
      <div class="smart-table-operate-block">
        <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit" :disabled="valid">提交</a-button>
      </div>
    </template>
  </a-drawer>
</template>
<script setup lang="ts">
import _ from 'lodash'
import { message } from 'ant-design-vue'
import { errorSentry } from '@/lib/error-sentry'
import failImg from '@/assets/images/notice/failImg.png'
import { useQuery } from '@/hooks/web/use-query-hook'
import { PAGE_SIZE_OPTIONS } from '@/constants/system/common-const'
import { warningRulesApi } from '@/api/business/storage/warehouse-api'
import { WARNING_TYPE_ENUM } from '@/constants/business/storage/warning/warning-const'
// emit
const emit = defineEmits(['reload-list'])
// ========== 抽屉 ==========
const visible = ref(false)

function showDrawer() {
  visible.value = true
  onSearch()
}

function onClose() {
  visible.value = false
  selectedRowKeyList.value = []
  dateTime.value = undefined
  resetQuery()
}
defineExpose({
  showDrawer
})
// ========== 查询经销商所属商品 ==========
const columns = [
  {
    title: '图片',
    dataIndex: 'img',
    width: 80
  },
  {
    title: '商品名称',
    dataIndex: 'goods_name',
    width: '20%'
  },
  {
    title: '库存数量',
    dataIndex: 'total_quantity'
  },
  {
    title: '单位',
    dataIndex: 'unit_name'
  },
  {
    title: '规格',
    dataIndex: 'spec_name'
  },
  {
    title: '商品编码',
    dataIndex: 'no'
  }
]
const { queryForm, tableData, tableLoading, total, onSearch, resetQuery, queryData } = useQuery({
  fetchDataApi: async ({ page, limit, filter }) => {
    const params = {
      ...filter,
      page,
      limit
    }
    const res = await warningRulesApi.queryGoodsList(params)
    return {
      list: res.data.data,
      total: res.data.total
    }
  },
  queryFormFilter: {
    type: WARNING_TYPE_ENUM.STAY.value,
    keyword: '',
    goods_no: ''
  },
  queryFormOp: {}
})
const selectedRowKeyList = ref<number[]>([])
function onSelectChange(selectedRowKeys: number[]) {
  selectedRowKeyList.value = selectedRowKeys
}
onMounted(queryData)

// ========== 提交 ==========
const dateTime = ref()
const valid = computed(() => {
  if (isNaN(dateTime.value)) {
    return true
  }
  if (dateTime.value < 1) {
    return true
  }
  if (selectedRowKeyList.value.length === 0) {
    return true
  }
  return false
})
async function onSubmit() {
  try {
    const params = {
      ids: selectedRowKeyList.value.join(','),
      type: WARNING_TYPE_ENUM.STAY.value,
      value: dateTime.value
    }
    const res = await warningRulesApi.create(params)
    message.success(res.msg)
    onSearch()
  } catch (error) {
    message.error(error.msg)
    errorSentry.captureError(error)
  }
}
</script>
<style scoped>
.title {
  margin-right: 5px;
  cursor: pointer;
}
</style>
